package cn.learn.controller.cargo;

import cn.learn.base.BaseController;
import cn.learn.domain.cargo.Export;
import cn.learn.domain.cargo.ExportProduct;
import cn.learn.domain.cargo.ExportProductExample;
import cn.learn.service.cargo.ExportProductService;
import cn.learn.service.cargo.ExportService;
import cn.learn.utils.commons.BeanMapUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/cargo/export")
public class PdfController extends BaseController {

    @Reference
    private ExportService exportService;
    @Reference
    private ExportProductService exportProductService;

    /**
     * PDF 生成
     * @param id
     */
    @RequestMapping(value = "/exportPdf", name = "paf报运单导出")
    public void exportPdf(String id) {
        try {// 根据报运单的id获取报运单
            Export export = exportService.findById(id);
            // 动态导入报运单  map--$P
            Map<String, Object> map = BeanMapUtils.beanToMap(export);
            // 动态导入货物的数据  list--$F
            ExportProductExample exportProductExample = new ExportProductExample();
            ExportProductExample.Criteria criteria = exportProductExample.createCriteria();
            criteria.andExportIdEqualTo(id);
            List<ExportProduct> list = exportProductService.findAll(exportProductExample);
            // 读取模板动态填充
            String path = session.getServletContext().getRealPath("/jasperPDF/export.jasper");
            FileInputStream fileInputStream = new FileInputStream(path);
            JRBeanCollectionDataSource jrBeanCollectionDataSource = new JRBeanCollectionDataSource(list);
            JasperPrint jasperPrint = JasperFillManager.fillReport(fileInputStream, map, jrBeanCollectionDataSource);
            JasperExportManager.exportReportToPdfStream(jasperPrint,response.getOutputStream());
        } catch (FileNotFoundException | JRException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
